package main

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

func GetCurrentPath() (string, error) {
	s, err := exec.LookPath(os.Args[0])
	i := strings.LastIndex(s, "\\")
	path := string(s[0 : i+1])
	return path, err
}

func CmdAndChangeDirToFile(fileName, dir, commandName string, params []string) error {
	Path, err := GetCurrentPath()
	if err != nil {
		return err
	}
	Path += "logs/"
	os.MkdirAll(Path, os.ModePerm)
	f, _ := os.Create(Path + fileName) //创建文件
	defer f.Close()
	cmd := exec.Command(commandName, params...)
	fmt.Println("CmdAndChangeDirToFile", dir, cmd.Args)
	//StdoutPipe方法返回一个在命令Start后与命令标准输出关联的管道。Wait方法获知命令结束后会关闭这个管道，一般不需要显式的关闭该管道。
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println("cmd.StdoutPipe: ", err)
		return err
	}
	cmd.Stderr = os.Stderr
	cmd.Dir = dir
	err = cmd.Start()
	if err != nil {
		return err
	}
	//创建一个流来读取管道内内容，这里逻辑是通过一行一行的读取的
	reader := bufio.NewReader(stdout)
	//实时循环读取输出流中的一行内容
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		_, _ = f.WriteString(line) //写入文件(字节数组)
		f.Sync()
	}
	_, _ = f.WriteString("=================处理完毕========================") //写入文件(字节数组)
	f.Sync()
	err = cmd.Wait()
	return err
}

func launchHandle(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "<h1>Hello,this is my deploy page</h1>")
	CmdAndChangeDirToFile("cmd.log", ".", "/bin/bash", []string{"-c", "./deploy.sh"})
}

func main() {
	http.HandleFunc("/", launchHandle)
	http.ListenAndServe(":5000", nil)
}
